package com.etoak.service.impl;

import com.etoak.common.vo.TourVO;
import com.etoak.entity.Pic;
import com.etoak.entity.Tags;
import com.etoak.entity.Tour;
import com.etoak.mapper.PicMapper;
import com.etoak.mapper.TagsMapper;
import com.etoak.mapper.TourMapper;
import com.etoak.service.TourService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Service
public class TourServiceImpl implements TourService {

    @Autowired
    TourMapper tourMapper;

    @Autowired
    PicMapper picMapper;

    @Autowired
    TagsMapper tagsMapper;

    @Override
    @Transactional
    public int addTour(TourVO vo) {
        Tour tour = new Tour();
        BeanUtils.copyProperties(vo,tour);
        int insert = tourMapper.insert(tour);
        int id = tour.getId();
        String[] tags = vo.getTags();
        for (String tag:tags){
            Tags tag1 = new Tags();
            tag1.setValue(tag);
            tag1.setTourId(id);
            tagsMapper.insert(tag1);
        }

        picMapper.updateByTourId(id);
        return insert;
    }

    @Override
    @Transactional
    public List<TourVO> queryTour(TourVO vo) {
        List<TourVO> tours = tourMapper.queryTour(vo);
        for (TourVO tour:tours){
            Pic pic = picMapper.queryById(tour.getId());
            tour.setPath(pic.getUrl());
        }
        return tours;
    }

    @Override
    @Transactional
    public TourVO queryById(int id) {
        TourVO vo = tourMapper.queryById(id);
        List<Pic> pics =  picMapper.queryPaths(id);
        List<Tags> tags = tagsMapper.queryByTagList(id);
        List<String> paths = new ArrayList<>();
        List<String> tagList = new ArrayList<>();
        for (Pic pic:pics){
            paths.add("http://localhost:9000"+pic.getUrl());
        }
        for (Tags tag:tags){
            tagList.add(tag.getValue());
        }
        vo.setPaths(paths);
        vo.setTagList(tagList);

        tourMapper.updateBrowse(id);

        return vo;
    }
}
